﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VacationDaysCommons;
using System.Collections.ObjectModel;
using VacationDaysDatabase;

namespace VacationDaysClient.CustomControls
{
    /// <summary>
    /// Interaction logic for PMUserVacationRequests.xaml
    /// </summary>
    public partial class PMUserVacationRequests : UserControl
    {
        private Guid currentPMId;

        private List<VDVacationRequest> employeesPendingRequests;

        public ObservableCollection<VDEmployee> _pmEmployeesCollection = new ObservableCollection<VDEmployee>();
        public ObservableCollection<VDEmployee> PMEmployeesCollection { get { return _pmEmployeesCollection; } }

        private void RefreshData()
        {

            using (VDRequestServiceClient vr = new VDRequestServiceClient())
            {
                employeesPendingRequests = vr.GetPendingRequestsByPM(currentPMId).ToList();
            }

            using (VDUserServiceClient vu = new VDUserServiceClient())
            {
                var emplist = vu.GetEmployeesByPM(currentPMId);


                _pmEmployeesCollection.Clear();
                _pmEmployeesCollection.Add(new VDEmployee() { Id = Guid.Empty, UserName = "ALL" });//add dummy ALL employees - for filter
                foreach (var emp in emplist)
                {
                    _pmEmployeesCollection.Add(emp);
                }
            
                employeeSelector.SelectedIndex = 0;
            }
        }

        private void RefreshPMEmployeeVacationDaysByEmpId(Guid empId)
        {
            if (empId == Guid.Empty)
            {
                // list all
                listView1.ItemsSource = new ObservableCollection<VDVacationRequest>(employeesPendingRequests);
            }
            else
            {
                //list for selected employee
                listView1.ItemsSource = new ObservableCollection<VDVacationRequest>(employeesPendingRequests.FindAll(r => r.UserID == empId));
            }
        }

        public PMUserVacationRequests()
        {
            InitializeComponent();
        }

        public PMUserVacationRequests(Guid currentPM)
        {
            currentPMId = currentPM;
            InitializeComponent();
            RefreshData();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            button1.ContextMenu.IsOpen = true;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            button2.ContextMenu.IsOpen = true;
        }

        private void employeeSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedEmployee = (employeeSelector.SelectedItem as VDEmployee);
            if (selectedEmployee != null)
            {
                RefreshPMEmployeeVacationDaysByEmpId(selectedEmployee.Id);
            }
        }

        private void RejectMultiple(List<VDVacationRequest> requests, string reasonText)
        {
            var requestsToUpdate = requests;
            foreach (var req in requestsToUpdate)
            {
                req.RequestState = VDRequestState.Rejected;
            }
          
            using (VDRequestServiceClient vr = new VDRequestServiceClient()){
                var updatedRequestIDs = vr.UpdateRequests(requestsToUpdate.ToArray());
                if (updatedRequestIDs.Count() > 0)
                {
                    foreach (var reqID in updatedRequestIDs)
                    {
                        var request = requestsToUpdate.Single(r => r.Id == reqID);
                        if (request != null)
                        {
                            string msgText = string.Format(@"Your request for holiday with start date {0}, and a duration of {1} working day(s) had been REJECTED.\r\nReason: {2}", request.StartDate, request.Duration, reasonText);
                            using (VDMessengerServiceClient vm = new VDMessengerServiceClient())
                            {
                                vm.SendUserMessage(new VDMessageItem()
                                {
                                    MessageType = VDMessageType.VacationRejected,
                                    MessageText = msgText,
                                    SenderId = currentPMId,
                                    UserId = request.UserID,
                                    Timestamp = DateTime.Now,
                                });
                            }
                        }
                    }
                }
            }

           RefreshData();

        }

        private void ApproveMultiple(List<VDVacationRequest> requests)
        {
            var requestsToUpdate = requests;
            foreach (var req in requestsToUpdate)
            {
                req.RequestState = VDRequestState.Approved;
            }
           
            using (VDRequestServiceClient vr = new VDRequestServiceClient())
            {
                var updatedRequestIDs = vr.UpdateRequests(requestsToUpdate.ToArray());
                if (updatedRequestIDs.Count() > 0)
                {
                    foreach (var reqID in updatedRequestIDs)
                    {
                        var request = requestsToUpdate.Single(r => r.Id == reqID);
                        if (request != null)
                        {
                            string msgText = string.Format(@"Your request for holiday with start date {0}, and a duration of {1}working day(s) had been APPROVED.",
                                                            request.StartDate, request.Duration);
                            using (VDMessengerServiceClient vm = new VDMessengerServiceClient())
                            {


                                vm.SendUserMessage(new VDMessageItem()
                                    {
                                        MessageType = VDMessageType.VacationApproved,
                                        SenderId = currentPMId,
                                        UserId = request.UserID,
                                        Timestamp = DateTime.Now,
                                        MessageText = msgText
                                    });
                            }
                        }
                    }
                }
            }
            RefreshData();
        }

        private void ApproveAllMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var requestList = listView1.Items.OfType<VDVacationRequest>().ToList();
            ApproveMultiple(requestList);
            
        }

        private void ApproveSelectedMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var requestList = listView1.SelectedItems.OfType<VDVacationRequest>().ToList();
            ApproveMultiple(requestList);

        }

        private void RejectAllMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var requestList = listView1.Items.OfType<VDVacationRequest>().ToList();
            if (requestList.Count > 0)
            {
                var reasonTextEditor = new TextEditor();
                string reasonText = reasonTextEditor.ShowTextEditor("Enter reason for rejection:");
                RejectMultiple(requestList, reasonText);
            }
        }

        private void RejectSelectedMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var requestList = listView1.SelectedItems.OfType<VDVacationRequest>().ToList();
            if (requestList.Count > 0)
            {
                var reasonTextEditor = new TextEditor();
                string reasonText = reasonTextEditor.ShowTextEditor("Enter reason for rejection:");
                RejectMultiple(requestList, reasonText);
            }
        }
    }
}
